//
//  MainViewController.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/8/15.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SCLAlertView
import SVProgressHUD
import Kingfisher
import AVFoundation
import QRCodeReader



class MainViewController: UIViewController {
    
    @IBOutlet weak var menuButton: UIBarButtonItem!
    
    
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var centerLabel: UILabel!
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var managerCancelButton: UIButton!
    @IBOutlet weak var managerSelectAllButton: UIButton!
    
    
    @IBOutlet weak var managerButton: UIButton!
    @IBOutlet weak var collectionView: UICollectionView!
    
    /// bottom view
    @IBOutlet weak var stackView: UIStackView!
    @IBOutlet weak var bottomScanButton: UIButton!
    @IBOutlet weak var moveButton: UIButton!
    @IBOutlet weak var deleteButton: UIButton!
    enum ScanType {
        case diannei
        case shangpin
    }
    var scanType: ScanType = .shangpin
    
    var ifManager = false
    var selectedRow = [Int]()
    
    
    var classId: Int? = nil
    let materialHelper = MaterialHelper()
    var materials = [Material]()
    
    var images = [UIImage?]()
    lazy var readerVC: QRCodeReaderViewController = {
        let builder = QRCodeReaderViewControllerBuilder {
            $0.reader = QRCodeReader(metadataObjectTypes: [AVMetadataObject.ObjectType.qr.rawValue], captureDevicePosition: .back)
            $0.showTorchButton = true
        }
        
        return QRCodeReaderViewController(builder: builder)
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if self.revealViewController() != nil {
            //self.revealViewController().delegate = self
            
            menuButton.target = self.revealViewController()
            menuButton.action = #selector(self.revealViewController().revealToggle(_:))
            view.addGestureRecognizer(revealViewController().panGestureRecognizer())
            view.addGestureRecognizer(revealViewController().tapGestureRecognizer())
            
        }
        if !User.isLogin {
            let loginVC = LoginController()
            loginVC.delegate = self
            let navigationController = UINavigationController(rootViewController: loginVC)
            self.present(navigationController, animated: true, completion: nil)
        } else {
            prepareMainVC(state: App.state)
        }
        
        collectionView.backgroundColor = #colorLiteral(red: 0.9369913936, green: 0.9376766086, blue: 0.9578072429, alpha: 1)
        collectionView.delegate = self
        collectionView.dataSource = self
        
        setUpView()
    }
    private func setUpView() {
        bottomScanButton.layer.cornerRadius = 10.0
        moveButton.layer.cornerRadius = 10.0
        moveButton.addTarget(self, action: #selector(moveButtonTapped(_:)), for: .touchUpInside)
        deleteButton.layer.cornerRadius = 10.0
        deleteButton.addTarget(self, action: #selector(deleteButtonTapped(_:)), for: .touchUpInside)
        managerCancelButton.layer.cornerRadius = 10.0
        managerCancelButton.addTarget(self, action: #selector(deSelectAllButtonTapped(_:)), for: .touchUpInside)
        managerSelectAllButton.layer.cornerRadius = 10.0
        managerSelectAllButton.addTarget(self, action: #selector(selectAllButtonTapped(_:)), for: .touchUpInside)
    }
    @IBAction func leftButtonTapped(_ button: UIButton!) {
        let vc = storyboard?.instantiateViewController(withIdentifier: "ClassifyVC") as! ClassifyVC
        vc.delegate = self
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func rightButtonTapped(_ button: UIButton!) {
        if classId == nil {
            let alert = SCLAlertView()
            alert.showWarning("请选择一个品类", subTitle: "若未创建，请先创建分类与品类以添加物料！")
        } else {
            let vc = storyboard?.instantiateViewController(withIdentifier: "CreateItemVC") as! CreateItemVC
            vc.classId = classId!
            vc.delegate = self
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    
    func updateManagerState() {
        ifManager = !ifManager
        if ifManager {
            collectionView.allowsMultipleSelection = true
            managerButton.setTitle("取消", for: .normal)
            UIView.animate(withDuration: 0.7, animations: {
                self.bottomScanButton.center.y += 70
                self.bottomScanButton.alpha = 0.0
                self.stackView.center.y -= 55
                self.stackView.alpha = 1.0
                
                self.leftButton.center.x -= 45
                self.leftButton.alpha = 0.0
                self.managerCancelButton.center.x += 85
                self.managerCancelButton.alpha = 1.0
                
                self.rightButton.center.x += 45
                self.rightButton.alpha = 0.0
                self.managerSelectAllButton.center.x -= 85
                self.managerSelectAllButton.alpha = 1.0
                
            })
        } else {
            managerButton.setTitle("管理", for: .normal)
            collectionView.allowsMultipleSelection = false
            if let selectedIndexPath = collectionView.indexPathsForSelectedItems {
                if selectedIndexPath.count == 1 {
                    let cell = collectionView.cellForItem(at: selectedIndexPath[0])
                    cell?.isSelected = false
                }
            }
            UIView.animate(withDuration: 0.7, animations: {
                self.bottomScanButton.center.y -= 70
                self.bottomScanButton.alpha = 1
                self.stackView.center.y += 55
                self.stackView.alpha = 0.0
                
                self.leftButton.center.x += 45
                self.leftButton.alpha = 1.0
                self.managerCancelButton.center.x -= 85
                self.managerCancelButton.alpha = 0.0
                
                self.rightButton.center.x -= 45
                self.rightButton.alpha = 1.0
                self.managerSelectAllButton.center.x += 85
                self.managerSelectAllButton.alpha = 0.0
            })
        }
    }
    @IBAction func managerButtonTapped(_ sender: UIButton!) {
        updateManagerState()
    }
    
    @objc func moveButtonTapped(_ button: UIButton!) {
        selectedRow = []
        guard let selectedItems = collectionView.indexPathsForSelectedItems else {
            return
        }
        guard selectedItems.count > 0 else {
            return
        }
        for i in 0 ..< selectedItems.count {
            selectedRow.append(selectedItems[i].row)
        }
        print(selectedItems)
        let vc = storyboard?.instantiateViewController(withIdentifier: "ClassifyVC") as! ClassifyVC
        vc.delegate = self
        vc.ifManager = true
        let nav = UINavigationController(rootViewController: vc)
        self.present(nav, animated: true, completion: nil)
    }

    @objc func deleteButtonTapped(_ button: UIButton!) {
        selectedRow = []
        guard let selectedItems = collectionView.indexPathsForSelectedItems else {
            return
        }
        guard selectedItems.count > 0 else {
            return
        }
        for i in 0 ..< selectedItems.count {
            selectedRow.append(selectedItems[i].row)
        }
        var ids = [Int]()
        for i in selectedRow {
            ids.append(materials[i].materialId)
        }
        print(ids)
        SVProgressHUD.show()
        materialHelper.deleteMaterials(ids: ids) { (success) in
            self.updateManagerState()
            if success {
                let set = Set(self.selectedRow)
                self.materials = self.materials
                    .enumerated()
                    .filter { !set.contains($0.offset) }
                    .map { $0.element }
                self.collectionView.performBatchUpdates({
                    self.collectionView.deleteItems(at: selectedItems)
                }, completion: nil)
                SVProgressHUD.showSuccess(withStatus: "成功！")
            } else {
                SVProgressHUD.showError(withStatus: "失败！")
            }
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }
    @objc func selectAllButtonTapped(_ button: UIButton!) {
        for i in 0 ..< collectionView.numberOfItems(inSection: 0) {
            collectionView.selectItem(at: IndexPath(row: i, section: 0), animated: true, scrollPosition: .bottom)
        }
    }
    @objc func deSelectAllButtonTapped(_ button: UIButton!) {
        for i in 0 ..< collectionView.numberOfItems(inSection: 0) {
            collectionView.deselectItem(at: IndexPath(row: i, section: 0), animated: true)
        }
    }
    @IBAction func scanBtTapped(_ button: UIButton!) {
        readerVC.delegate = self
        
        // Or by using the closure pattern
        readerVC.completionBlock = { (result: QRCodeReaderResult?) in
            print(result ?? "")
        }
        
        // Presents the readerVC as modal form sheet
        navigationController?.pushViewController(readerVC, animated: true)
    }
    
}

extension MainViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MainItemCell", for: indexPath) as! MainItemCell
        cell.nameLabel.text = materials[indexPath.row].name
        cell.productCodeLabel.text = materials[indexPath.row].productCode
        if let url = URL(string: materials[indexPath.row].coverImage) {
            cell.imageView.kf.setImage(with: url)
        }
        cell.contentView.layer.cornerRadius = 10.0
        cell.contentView.layer.masksToBounds = true
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return materials.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if ifManager { //正在选item
            
        } else {
            let vc = MainItemDetailVC()
            vc.materialId = materials[indexPath.row].materialId
            navigationController?.pushViewController(vc, animated: true)
        }
    }
}



extension MainViewController: ClassifyDelegate {
    
    func didChooseClass(with parent: Classify, child: Classify) {
        if ifManager {
            SVProgressHUD.show()
            var classIds = [Int]()
            for i in selectedRow {
                classIds.append(materials[i].materialId)
            }
            materialHelper.changeClass(to: child.classId, materialIds: classIds, completeHandler: { (success) in
                self.updateManagerState()
                if success {
                    guard self.classId! != child.classId else {
                        SVProgressHUD.dismiss(withDelay: 1.5)
                        return
                    }
                    let set = Set(self.selectedRow)
                    self.materials = self.materials
                        .enumerated()
                        .filter { !set.contains($0.offset) }
                        .map { $0.element }
                    
                    self.collectionView.reloadData()
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
                SVProgressHUD.dismiss(withDelay: 1.5)
            })
        } else {
            SVProgressHUD.show()
            materialHelper.getAllMaterials(with: child.classId) { (success, data) in
                if success {
                    self.materials = data!
                    self.classId = child.classId
                    self.collectionView.reloadData()
                    self.centerLabel.text = child.name
                    SVProgressHUD.showSuccess(withStatus: "成功！")
                } else {
                    SVProgressHUD.showError(withStatus: "失败！")
                }
            }
            SVProgressHUD.dismiss(withDelay: 1.5)
        }
    }
}
extension MainViewController: LoginDelegate {
    //决定哪个VC作为MainVC
    func prepareMainVC(state: AppState) {
        switch App.state {
        case .AdminState:
            
            break
        case .ApplyState:
            let navigationVC = UINavigationController(rootViewController: ApplyStoreVC())
            self.revealViewController().setFront(navigationVC, animated: true)
        case .MemberState:
            let navigationVC = UINavigationController(rootViewController: MemberVC())
            self.revealViewController().setFront(navigationVC, animated: true)
        case .none:
            break
        }
    }
    func loginSuccess(from state: AppState) {
        prepareMainVC(state: state)
    }
}

extension MainViewController: CreateItemDelegate {
    func didCreateItem(material: Material) {
        materials.append(material)
        collectionView.performBatchUpdates({
            collectionView.insertItems(at: [IndexPath(row: materials.count-1, section: 0)])
        }, completion: nil)
    }
}

extension MainViewController: QRCodeReaderViewControllerDelegate {
    func handleScanCode(message: String) {
        let array = message.components(separatedBy: ":")
        guard array.count > 0, let materialId = Int(array[1]) else { return }
        if scanType == .shangpin {
            let detailVC = MainItemDetailVC()
            detailVC.materialId = materialId
            navigationController?.pushViewController(detailVC, animated: true)
        } else {
            
        }
    }
    func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) {
        handleScanCode(message: result.value)
    }
    func readerDidCancel(_ reader: QRCodeReaderViewController) {
        reader.stopScanning()
        navigationController?.popViewController(animated: true)
    }
    func leftButtonDidTapped() {
        scanType = .shangpin
    }
    func rightButtonDidTapped() {
        scanType = .diannei
    }
}
